/**
 * @desc:图片展示公共组件
 * @img: zjf商品图片url
 * @storeId： 门店id
 * @goodsId: 商品id
 * @size: 图片压缩比例和宽度 默认48，只支持48，64，84
 * @isMask: 是否需要展示商品遮罩信息（下架，售罄）
 * @goodsState: 商品状态
 * @carefullySelected: 是否是云仓严选商品 1:是 0:否
 */

import React, { useState } from "react";
import { Tooltip, Image } from "antd";
import Iconfont from "@/components/IconFont";
import styles from "./index.module.less";

const formatZjfImg = ({ img, storeId, size = 48 }) => {
	//检测图片是否是完整路径，如果不是需要拼接
	if (!img) {
		return `https://imgniu.zhaojiafang.com/no-img${size}.jpg`;
	}
	if (/^(http|https)/.test(img)) {
		if (/zhaojiafang/.test(img)) {
			return size ? `${img}_${size}x${size}` : img;
		} else {
			return img;
		}
	} else {
		return size
			? `https://imgniu.zhaojiafang.com/store/goods/${storeId}/${img}_${size}x${size}`
			: `https://imgniu.zhaojiafang.com/store/goods/${storeId}/${img}`;
	}
};

//获取商品状态 商品状态 0下架，1正常，10违规（禁售）
const renderMarkText = ({ size, goodsState, goodsStorage }) => {
	const height = `${size}px`;
	const maskStyle = {
		position: "absolute",
		top: 0,
		width: height,
		height: height,
		textAlign: "center",
		lineHeight: height,
		color: "#fff",
		background: "rgba(0, 0, 0, 0.5)"
	};

	if (goodsState || goodsState == 0) {
		if (goodsState == 1 || goodsState == 88) {
			if (goodsStorage == 0) {
				return <div style={maskStyle}>已售罄</div>;
			}
			return null;
		} else {
			return <div style={maskStyle}>已下架</div>;
		}
	} else {
		return null;
	}
};

//云仓严选图标
const renderCloudIcon = () => {
	return (
		<Tooltip title={<span className="common-color4">云仓严选商品，代发渠道支持云仓严选渠道进行发货</span>} color="#fff">
			<div className={styles.iconBox}>
				<Iconfont className={styles.icon} type="iconcloudhouse" />
			</div>
		</Tooltip>
	);
};

export default ({ img, storeId, size = 48, goodsState, goodsStorage, style = {}, isMask = false, isCloudIcon = false }) => {
	const src = formatZjfImg({ img, storeId, size });
	const previewSrc = formatZjfImg({ img, storeId, size: null });
	const [visible, setVisible] = useState(false);
	return (
		<div
			className={styles[`imgWrap${size}`]}
			onClick={() => {
				setVisible(true);
			}}
			style={{ position: "relative", cursor: 'pointer', ...style }}
		>
			<img src={src} referrerPolicy="no-referrer" style={{ width: "100%", height: "100%" }} />
			<Image
				style={{ display: "none" }}
				src={src}
				preview={{
					visible,
					src: previewSrc,
					onVisibleChange: value => {
						setVisible(value);
					}
				}}
			/>
			{isMask && renderMarkText({ size, goodsState, goodsStorage })}
			{isCloudIcon == 1 && renderCloudIcon()}
		</div>
	);
};
